<template>
    <div>
        <el-form :model="form" :rules="rules" ref="formRef">

            <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" />
            </el-form-item>

            <el-form-item label="密码" prop="password">
                <el-input v-model="form.password" type="password" />
            </el-form-item>

            <el-form-item label="确认密码" prop="confirmPassword">
                <el-input v-model="form.confirmPassword" type="password" />
            </el-form-item>

            <el-form-item label="邮箱验证码" prop="emailCode">
                <el-input v-model="form.emailCode" style="width: 60%" />
                <el-button :disabled="isSending" @click="sendEmailCode">{{ buttonText }}</el-button>
            </el-form-item>

            <el-button type="primary" @click="register">注册</el-button>
        </el-form>

        <el-link @click="router.push({ name: 'Login' })" type="primary">已有账号？点击登录</el-link>
    </div>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router'
import axios from 'axios';
import { UserStore } from '../store/user';
import { TokenStore } from '../store/user';
import { da } from 'element-plus/es/locales.mjs';

const router = useRouter()

const form = reactive({
    email: '3495789702@qq.com',
    password: '111111q',
    confirmPassword: '111111q',
    emailCode: ''
});

const formRef = ref(null);

// 验证密码是否一致
const validatePass = (rule, value, callback) => {
    if (value !== form.password) {
        callback(new Error('两次输入密码不一致!'));
    } else {
        callback();
    }
};

const rules = {
    email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        // 添加正则表达式验证
        { 
            pattern: /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z0-9]{6,16}$/, 
            message: '密码长度为 6 到 16 位，且必须同时包含字母和数字', 
            trigger: 'blur' 
        }
    ],
    confirmPassword: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        { validator: validatePass, trigger: 'blur' }
    ],
    emailCode: [
        { required: true, message: '请输入邮箱验证码', trigger: 'blur' },
        { min: 6, message: '验证码长度为6位', trigger: 'blur' }
    ]
};

const isSending = ref(false);
const buttonText = ref('发送验证码');

// 发送邮箱验证码
const sendEmailCode = async () => {
    try {
        if (!isSending.value) {
            isSending.value = true;
            buttonText.value = '发送中...';
            const response = await axios.post('http://localhost:8080/zhongjianyu.cat.com/api/user/emailCode', { email: form.email });
            setTimeout(() => {
                isSending.value = false;
                buttonText.value = '重新发送';
                ElMessage.success('验证码已发送，请查收');
            }, 2000);
        }
    } catch (error) {
        isSending.value = false;
        buttonText.value = '重新发送';
        console.error('发送验证码失败:', error);
        ElMessage.error('发送验证码失败，请稍后再试');
    }
};

// 注册函数
const register = async () => {
    try {
        const valid = await formRef.value.validate();
        if (valid) {
            const response = await axios.post('http://localhost:8080/zhongjianyu.cat.com/api/user/register', form);
            console.log(response);
            if (response.data.code !== 200) {
                ElMessage.error(response.data.msg);
                return false;
            }
            ElMessage.success('注册成功!');
            const userStore = UserStore();
            const tokenStore = TokenStore();
            const dat = response.data.data;
            userStore.saveUser(dat.user);
            tokenStore.saveAccessToken(dat.accessToken);
            tokenStore.saveRefreshToken(dat.refreshToken);
            router.push({ name: 'Home' });
        } else {
            ElMessage.error('请正确填写信息');
            return false;
        }
    } catch (error) {
        console.error('注册失败:', error);
        ElMessage.error('注册失败，请稍后再试');
    }
};

</script>